<template>
  <div class="paper__form">
    <el-main v-loading="loading">
      <div class="paper__topBox">
        <TipCircle title1="新增" title2="试卷"></TipCircle>
      </div>
      <div class="paper__dialog">
        <div class="paper__dialog-left">
          <el-form ref="paperRef" :model="form" :rules="rules" label-width="82px">
            <el-form-item label="试卷名称" prop="paperName">
              <el-input v-model="form.paperName" placeholder="请输入试卷名称" />
            </el-form-item>
            <el-form-item label="课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择课程" clearable style="flex: 1" @change="changeCourse">
                <el-option v-for="dict in data.courseList" :key="dict.courseId" :label="dict.courseName"
                  :value="dict.courseId" />
              </el-select>
            </el-form-item>
            <el-form-item label="试卷类型" prop="paperType">
              <el-select v-model="form.paperType" placeholder="请选择类型" clearable style="flex: 1" @change="changePaperType">
                <el-option label="理论" :value="1" />
                <el-option label="实践" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="出卷人">
              <el-input v-model="data.paperAuthorName" disabled />
            </el-form-item>
            <el-form-item label="考试时长" prop="paperTime">
              <el-input-number v-model="form.paperTime" class="my-el-input-number" placeholder="请输入考试时长" style="flex: 1"
                data-unit="分钟" controls-position="right" size="large" @input.native="changePaperTime">
              </el-input-number>
            </el-form-item>
            <el-space fill>
              <el-alert type="warning" show-icon :closable="false">
                <p>选择试题后填写分值会自动计算总分数</p>
              </el-alert>
              <el-form-item label="总分数">
                <el-input disabled v-model="paperScoreCount" style="flex: 1" size="large"
                  placeholder="选择试题后填写分值会自动计算总分数" />
              </el-form-item>
            </el-space>

            <el-form-item label="及格分数" prop="passScore">
              <el-input-number v-model="form.passScore" :min="0" :max="paperScoreCount" style="flex: 1"
                controls-position="right" size="large" placeholder="及格分数不能大于总分" @input.native="changePassScore" />
            </el-form-item>

            <el-form-item label="题目类型" prop="questionType" v-if="form.paperType">
              <el-select v-model="form.questionType" placeholder="请选择题目类型" clearable style="flex: 1"
                @change="changeQuestionType">
                <el-option v-for="dict in questionTypeMap" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>

            <el-form-item v-show="form.questionType" required label="分值">
              <!-- TODO: 输入框有 data-unit属性 待明确目的 -->
              <el-input-number v-model="data.gradeList[form.questionType - 1]" class="my-el-input-number"
                placeholder="请输入分值" style="flex: 1" controls-position="right" size="large"
                @input.native="changeGradeList">
              </el-input-number>
            </el-form-item>
            <div v-show="isAuto">
              <el-divider>自动生成</el-divider>
              <div>
                <el-form-item label="简单题数量">
                  <el-input-number v-model="data.eduPaperResAutoVoList[form.questionType - 1]
                    .easyCount
                  " :min="0" :max="100" style="flex: 1" placeholder="请输入简单题数量" :step="1"
                    @input.native="changeEasyCount" />
                </el-form-item>

                <el-form-item label="普通题数量">
                  <el-input-number v-model="data.eduPaperResAutoVoList[form.questionType - 1]
                    .normalCount
                  " :min="0" :max="100" style="flex: 1" placeholder="请输入普通题数量" :step="1"
                    @input.native="changeNormalCount" />
                </el-form-item>

                <el-form-item label="困难题数量">
                  <el-input-number v-model="data.eduPaperResAutoVoList[form.questionType - 1]
                    .hardCount
                  " :min="0" :max="100" style="flex: 1" placeholder="请输入困难题数量" :step="1"
                    @input.native="changeHardCount" />
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
        <div class="paper__dialog-right">
          <div v-show="isAuto" class="paper__dialog-right-tier" @click.prevent="() => { }"></div>
          <el-form :model="data.questionQueryParams" ref="queryRef" :inline="true" label-width="52px">
            <el-form-item label="题目" prop="questionTitle">
              <el-input v-model="data.questionQueryParams.questionTitle" placeholder="请输入题目名称" clearable
                @keyup.enter="handleQuestionQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuestionQuery">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-main v-loading="questionLoading">
            <div v-if="data.questionList && data.questionList.length" class="question_list_wrapper">
              <Question :questionList="data.questionList" :source="1">
                <template #handle="{ data }">
                  <el-button v-if="data.selected || isExistQuestionList(data.questionId)"
                    @click="cancelQuestion(data)">取消选择</el-button>

                  <el-button v-else type="primary" size="small" :icon="Plus" @click="addQuestion(data)">加入试卷</el-button>
                </template>
              </Question>
            </div>
            <el-empty v-else description="暂无数据" />
          </el-main>
            <div class="pagination">
              <pagination v-show="questionTotal > 0" :total="questionTotal" v-model:page="data.questionQueryParams.pageNum"
        v-model:limit="data.questionQueryParams.pageSize" @pagination="getQuestionList" />
            </div>
        </div>
      </div>
      <div class="dialog-footer">
        <div class="dialog-footer-left">
          <div v-if="!isEdit && form.paperType === 1">
            <el-button v-if="isAuto" type="primary" @click="editAuto">手动生成</el-button>
            <el-button v-else type="primary" @click="editAuto">自动生成</el-button>
          </div>
        </div>
        <div class="dialog-footer-right">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">生 成</el-button>
        </div>
      </div>
    </el-main>
  </div>
</template>

<script setup name="Paper">
import {
  getPaper,
  addPaper,
  updatePaper,
  paperIdByQuestionList,
  getPaperAuthorName,
  listQuestion
} from "@/api/testCenter/paper";

import { queryCourseList } from '@/api/analyse.js'
import { Plus } from "@element-plus/icons-vue";

import TipCircle from "@/components/TipCircle";
import Question from "@/components/Question";
import { computed } from "vue";

const emits = defineEmits(["cancel", "success"]);

const props = defineProps({
  paper: {
    type: Object,
    default: {},
  },
});

const { proxy } = getCurrentInstance();

const loading = ref(true);
const isEdit = ref(true);
const questionLoading = ref(true);
const questionTotal = ref(0);

// 自动生成
const isAuto = ref(false);



const getEduPaperResAutoVoList = () => {
  const eduPaperResAutoVoList = []
  for (let index = 0; index < 6; index++) {
    eduPaperResAutoVoList.push({
      easyCount: 0,
      normalCount: 0,
      hardCount: 0,
    })
  }
  return eduPaperResAutoVoList
}
const data = reactive({
  paperAuthorName: "",
  courseList: [],
  queryCourseList: [],
  // 手动生成题类型分数
  gradeList: [],
  // 手动生成所选题
  eduPaperDetailList: [],
  currentSelectedPaperShow: {},
  // 自动生成配置
  eduPaperResAutoVoList: getEduPaperResAutoVoList(),
  form: {
    questionType: null,
  },
  questionList: [],
  questionQueryParams: {
    pageNum: 1,
    pageSize: 15,
    courseId: null,
    questionType: 1,
    hardLevel: null,
    questionTitle: "",
    questionTitleEnclosure: null,
    questionAnswers: null,
    rightAnswers: null,
    deleted: null,
    year: null,
  },
  rules: {
    paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
    courseId: [{ required: true, message: "请选择课程", trigger: "change" }],
    paperType: [{ required: true, message: "请选择试卷类型", trigger: "change" }],
    paperTime: [{ required: true, message: "请输入考试时间", trigger: "blur" }],
    passScore: [{ required: true, message: "请输入及格分数", trigger: "blur" }],
  },
  paperScoreCount: "",
  eduPaperDetailCount: [0, 0, 0, 0, 0, 0],
});

const { form, rules } = toRefs(data);



const paperScoreCount = computed(() => {
  const danXuanScore = data.gradeList[0] || 0;
  const duoXuanScore = data.gradeList[1] || 0;
  const panDuanScore = data.gradeList[2] || 0;
  const tiankongScore = data.gradeList[3] || 0;
  const chengxuScore = data.gradeList[4] || 0;
  const jiandaScore = data.gradeList[5] || 0;
  let danxuanCount = 0;
  let duoXuanCount = 0;
  let panDuanCount = 0;
  let tiankongCount = 0;
  let chengxuCount = 0;
  let jiandaCount = 0;

  if (isAuto.value) {
    danxuanCount =
      data.eduPaperResAutoVoList[0].easyCount +
      data.eduPaperResAutoVoList[0].normalCount +
      data.eduPaperResAutoVoList[0].hardCount;
    duoXuanCount =
      data.eduPaperResAutoVoList[1].easyCount +
      data.eduPaperResAutoVoList[1].normalCount +
      data.eduPaperResAutoVoList[1].hardCount;
    panDuanCount =
      data.eduPaperResAutoVoList[2].easyCount +
      data.eduPaperResAutoVoList[2].normalCount +
      data.eduPaperResAutoVoList[2].hardCount;
  } else {
    danxuanCount = data.eduPaperDetailCount[0];
    duoXuanCount = data.eduPaperDetailCount[1];
    panDuanCount = data.eduPaperDetailCount[2];
    tiankongCount = data.eduPaperDetailCount[3];
    chengxuCount = data.eduPaperDetailCount[4];
    jiandaCount = data.eduPaperDetailCount[5];
  }

  const danXuanScoreCount = danXuanScore * danxuanCount;
  const duoXuanScoreCount = duoXuanScore * duoXuanCount;
  const panDuanScoreCount = panDuanScore * panDuanCount;
  const tiankongScoreCount = tiankongScore * tiankongCount;
  const chengxuScoreCount = chengxuScore * chengxuCount;
  const jiandaScoreCount = jiandaScore * jiandaCount;

  return danXuanScoreCount + duoXuanScoreCount + panDuanScoreCount + tiankongScoreCount + chengxuScoreCount + jiandaScoreCount;
});

function isExistQuestionList(id) {
  return data.eduPaperDetailList.indexOf(id) >= 0;
}
function editAuto() {
  isAuto.value = !isAuto.value;
}
function changeQuestionType(val) {
  console.log("🚀 ~ changeQuestionType ~ val:", val)
  data.questionQueryParams.questionType = val;
  handleQuestionQuery();
}
function changePaperTime(val) {
  form.value.paperTime = val;
}
function changePassScore(val) {
  form.value.passScore = val;
}
function changeEasyCount(val) {
  data.eduPaperResAutoVoList[form.value.questionType - 1].easyCount = val;
}
function changeNormalCount(val) {
  data.eduPaperResAutoVoList[form.value.questionType - 1].normalCount = val;
}
function changeHardCount(val) {
  data.eduPaperResAutoVoList[form.value.questionType - 1].hardCount = val;
}
function changeGradeList(val) {
  data.gradeList[form.value.questionType - 1] = val;
}

// 取消按钮
function cancel() {
  reset();
  emits("cancel");
}

// 表单重置
function reset() {
  form.value = {
    questionType: 1,
    paperId: null,
    paperName: null,
    courseId: null,
    paperAuthorId: null,
    paperTime: null,
    paperScoreCount: null,
    passScore: null,
    paperStatus: null,
    danXuanScore: null,
    duoXuanScore: null,
    panDuanScore: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
  };
  data.paperScoreCount = "";

  questionTypeStr.value = "";
  data.eduPaperDetailList = [];
  data.eduPaperDetailCount = [0, 0, 0, 0, 0, 0];
  data.gradeList = [];
  data.eduPaperResAutoVoList = getEduPaperResAutoVoList()
  proxy.resetForm("paperRef");
}

function addQuestion(question) {
  question.selected = true;
  data.eduPaperDetailList.push(question.questionId);
  const index = form.value.questionType - 1;
  data.eduPaperDetailCount[index] = data.eduPaperDetailCount[index] += 1;
}

function cancelQuestion(question) {
  const delIndex = data.eduPaperDetailList.findIndex(
    (id) => `${id}` === `${question.questionId}`
  );
  const index = form.value.questionType - 1;

  if (data.eduPaperDetailCount[index] > 0) {
    data.eduPaperDetailCount[index] = data.eduPaperDetailCount[index] - 1;
  }

  data.eduPaperDetailList.splice(delIndex, 1);
  question.selected = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paperRef"].validate((valid) => {
    if (valid) {
      // 1手动生成 2自动生成
      form.value.insertType = isAuto.value ? 2 : 1;

      form.value.danXuanScore = data.gradeList[0] || 0;
      form.value.duoXuanScore = data.gradeList[1] || 0;
      form.value.panDuanScore = data.gradeList[2] || 0;
      form.value.tkScore = data.gradeList[3] || 0;
      form.value.cxScore = data.gradeList[4] || 0;
      form.value.jdScore = data.gradeList[5] || 0;

      form.value.paperScoreCount = paperScoreCount.value;

      const danXuanCount = data.eduPaperDetailCount[0];
      const duoXuanCount = data.eduPaperDetailCount[1];
      const panDuanCount = data.eduPaperDetailCount[2];
      const tkCount = data.eduPaperDetailCount[3];
      const cxCount = data.eduPaperDetailCount[4];
      const jdCount = data.eduPaperDetailCount[5];

      if (!form.value.danXuanScore && danXuanCount) {
        proxy.$modal.msgError("请选择单选题分数");
        return;
      }

      if (!form.value.duoXuanScore && duoXuanCount) {
        proxy.$modal.msgError("请选择多选题分数");
        return;
      }

      if (!form.value.panDuanScore && panDuanCount) {
        proxy.$modal.msgError("请选择判断题分数");
        return;
      }

      if (!form.value.tkScore && tkCount) {
        proxy.$modal.msgError("请选择填空题分数");
        return;
      }
      if (!form.value.cxScore && cxCount) {
        proxy.$modal.msgError("请选择程序题分数");
        return;
      }
      if (!form.value.jdScore && jdCount) {
        proxy.$modal.msgError("请选择简答题分数");
        return;
      }

      // 手动生成需要给题型分数
      if (!isAuto.value) {
        if (!(data.eduPaperDetailList && data.eduPaperDetailList.length)) {
          proxy.$modal.msgError("请选择试题");
          return;
        }
      }

      // 自动生成
      if (isAuto.value) {
        form.value.eduPaperResAutoVoList = data.eduPaperResAutoVoList.map(
          (row, index) => {
            return {
              ...row,
              questionType: index + 1,
            };
          }
        );
      }

      form.value.eduPaperDetailList = data.eduPaperDetailList.map((id) => ({
        questionId: id,
      }));

      if (form.value.paperId != null) {
        updatePaper(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          emits("success");
        });
      } else {
        addPaper(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          emits("success");
        });
      }
    }
  });
}

function handleQuestionQuery() {
  data.questionQueryParams.pageNum = 1;
  getQuestionList();
}

function getQuestionList() {
  questionLoading.value = true;
  if (props.paper && `${props.paper.paperId}`) {
     paperIdByQuestionList({
      ...data.questionQueryParams,
      paperId: props.paper.paperId,
      courseId: form.value.courseId,
    }).then(response => {
      data.questionList = response.rows;
      questionTotal.value = response.total;
      questionLoading.value = false;
    })
  } else {
    listQuestion({
      ...data.questionQueryParams,
      courseId: form.value.courseId || "",
    }).then((response) => {
      data.questionList = response.rows;
      questionTotal.value = response.total;
      questionLoading.value = false;
    });
  }
//   查询对应题目列表
 
}

function changeCourse() {
  data.questionQueryParams.pageNum = 1;
  getQuestionList();
}

const questionTypeList = [
  [
    {
      id: 1,
      name: "单选题",
    },
    {
      id: 2,
      name: "多选题",
    },
    {
      id: 3,
      name: "判断题",
    },
  ],
  [
    {
      id: 4,
      name: "填空题",
    },
    {
      id: 5,
      name: "程序题",
    },
    {
      id: 6,
      name: "简答题",
    },
  ]
]
let questionTypeMap = ref(null);

/**
 * @des TODO： questionTypeStr 的作用？？？
 */
const questionTypeStr = computed(() => {
  const row = questionTypeMap.value.find(
    (question) => `${data.form.questionType}` === `${question.id}`
  );
  return row.name || "";
});




/** 
 * @des 根据试卷类型的选择 决定题目类型的下拉选项
*/
function changePaperType(paperType) {
  questionTypeMap.value = questionTypeList[paperType - 1]
   if (paperType === 1) {
    data.form.questionType = 1
    data.questionQueryParams.questionType = 1
  } else {
    data.form.questionType = 4
    data.questionQueryParams.questionType = 4
  }
  getQuestionList()
}
async function getCourseList() {

  const courseRes = await queryCourseList();

  if (courseRes.code === 200 && courseRes.rows && courseRes.rows.length) {
    data.courseList = courseRes.rows;
    return;
  }

  data.courseList = [];
  proxy.$modal.msgError("该专业无课程数据");

}

async function init() {
  getCourseList()
  const [createPerson] = await Promise.all([
    getPaperAuthorName(),
    getQuestionList(),
  ]);

  if (createPerson.code === 200 && createPerson.data) {
    data.paperAuthorName = createPerson.data.paperAuthorName;
  }
}

// /** 新增按钮操作 */
async function handleAdd() {
  reset();
  await getQuestionList();
  loading.value = false;
}

/** 修改按钮操作 */
async function handleUpdate() {

  reset();

  const row = props.paper;
  const _paperId = row.paperId;
  let response = []
  let rows = {}
  let code = ''
  await getPaper(_paperId).then(async res => {
    console.log("🚀 ~ getPaper ~ res:", res)
    response = res
 
    if (response.data.paperType === 2) {
      data.questionQueryParams.questionType = 4
    } else {
      data.questionQueryParams.questionType = 1
    }
    await paperIdByQuestionList({
      ...data.questionQueryParams,
      paperId: _paperId,
      courseId: row.courseId,
    }).then(res => {
      console.log("🚀 ~ awaitgetPaper ~ res:", res)
      code = res.code
      rows = res.rows
      if (code === 200 && rows && rows.length) {
        data.eduPaperDetailList = rows
          .filter((row) => row.selected)
          .map((row) => row.questionId);
      }
    })
  })
   data.paperScoreCount = response.data.paperScoreCount;
  data.gradeList = [
    response.data.danXuanScore || 0,
    response.data.duoXuanScore || 0,
    response.data.panDuanScore || 0,
    response.data.tkScore || 0,
    response.data.jdScore || 0,
    response.data.cxScore || 0,
  ];

  const danxuanCount = rows.filter(
    (row) => row.questionType === "1" && row.selected
  ).length;
  const duoxuanCount = rows.filter(
    (row) => row.questionType === "2" && row.selected
  ).length;
  const panduanCount = rows.filter(
    (row) => row.questionType === "3" && row.selected
  ).length;
  const jdCount = rows.filter(
    (row) => row.questionType === "4" && row.selected
  ).length;
  const cxCount = rows.filter(
    (row) => row.questionType === "5" && row.selected
  ).length;
  const tkCount = rows.filter(
    (row) => row.questionType === "6" && row.selected
  ).length;

  data.eduPaperDetailCount = [danxuanCount, duoxuanCount, panduanCount, jdCount, cxCount, tkCount];

  form.value = {
    ...response.data,
  };
questionTypeMap.value = questionTypeList[response.data.paperType - 1]
   if (response.data.paperType === 1) {
    data.form.questionType = 1
  } else {
    data.form.questionType = 4
  }


  await getCourseList();
  await getQuestionList();

  loading.value = false;
}

init();

if (props.paper && `${props.paper.paperId}`) {
  isEdit.value = true;
  handleUpdate();
} else {
  isEdit.value = false;
  handleAdd();
}
</script>

<style lang="scss" scoped>
.my-el-input-number[data-unit] {
  --el-input-number-unit-offset-x: 35px;
  position: relative;
}

.my-el-input-number[data-unit]::after {
  content: attr(data-unit);
  height: 100%;
  display: flex;
  align-items: center;
  position: absolute;
  padding-right: 20px;
  font-size: 14px;
  top: 0;
  right: var(--el-input-number-unit-offset-x);
  color: #aaa;
}

.my-el-input-number[data-unit] .el-input__inner {
  padding-left: 30px;
  padding-right: calc(var(--el-input-number-unit-offset-x) + 12px);
}

.paper__form .paper__dialog-right .el-main {
  overflow-y: auto;
  padding-bottom: 70px;
}

.paper__form .el-main {
  padding: 0;
  height: calc(100vh - 130px);
  overflow-y: auto;
}
</style>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: 28px;
}

:deep(.pagination-container) {
  margin-top: 28px !important;
  height: 48px !important;
}

:deep(.paper__dialog-left .el-form-item) {
  margin-bottom: 25px;
}

:deep(.paper__dialog-left .el-divider) {
  margin-bottom: 38px;
  margin-top: 45px;
}

.paper {
  &__tips {
    font-size: 14px;
    color: #333;
  }

  &__topBox {
    margin-bottom: 15px;
  }

  &__dialog {
    display: flex;
    flex-direction: row;
    border-bottom: 1px solid #f2f3f5;
  }

  &__dialog-left {
    width: 355px;
    border-right: 1px solid #f2f3f5;
    padding-right: 14px;
    // padding-bottom: 200px;
  }

  &__dialog-right {
    position: relative;
    flex: 1;
    padding-left: 12px;
  }

  &__dialog-right-tier {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background-color: rgba($color: #e6e8eb, $alpha: 0.39);
  }

  &__list-count {
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
  }
}
.pagination{
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background-color: #fff;
}
</style>
